<!--
 * @Descripttion: 课堂分析详情-学生行为-学生发言
 * @version: V1.0.0.1
 * @Author: zhaozhenzhuo
 * @Date: 2025-10-29 17:30:28
 * @LastEditors: zhaozhenzhuo
 * @LastEditTime: 2025-10-29 17:30:28
-->
<template>
	<div class="student-speak-wrapper">
		<div class="module-title-wrapper">
			<p>学生发言</p>
			<img v-if="false" src="@/assets/images/lessonAnalysisDetails/text-edit-normal.png" />
		</div>
		<div class="detail">
			<p>
				本课堂师生问答互动共<span class="active"
					>{{
						aiScoreResult?.interactiveStudentNum || aiScoreResult?.interactiveStudentNum === 0
							? aiScoreResult?.interactiveStudentNum
							: '-'
					}}次</span
				>，学生总发言时间为<span
					v-if="interactiveResult?.total && interactiveResult?.total.interactiveTime >= 0"
					class="active"
					>{{ Math.floor(interactiveResult?.total.interactiveTime / 60000) }}分{{
						Math.floor(
							interactiveResult?.total.interactiveTime / 1000 -
								Math.floor(interactiveResult?.total.interactiveTime / 60000) * 60
						)
					}}秒</span
				><span v-else class="active">-分-秒</span>，占上课时间<span
					v-if="
						interactiveResult?.total &&
						(interactiveResult?.total.interactiveTime ||
							interactiveResult?.total.interactiveTime === 0) &&
						aiScoreResult?.totalTime
					"
					class="active"
					>{{
						interactiveResult?.total.interactiveTime / (aiScoreResult?.calTotalTime || 0) >= 1
							? 100
							: (
									(100 * interactiveResult?.total.interactiveTime) /
									(aiScoreResult?.calTotalTime || 0)
							  ).toFixed(1)
					}}%</span
				><span v-else class="active">-%</span>；有<span class="active"
					>{{
						aiScoreResult?.speakerStudentNum || aiScoreResult?.speakerStudentNum === 0
							? aiScoreResult?.speakerStudentNum
							: '-'
					}}位</span
				>学生参与发言，占全班人数<span
					v-if="
						(aiScoreResult?.speakerStudentNum || aiScoreResult?.speakerStudentNum === 0) &&
						lessonInfo?.teachingClassStudentCount
					"
					class="active"
					>{{
						aiScoreResult.speakerStudentNum / lessonInfo?.teachingClassStudentCount >= 1
							? 100
							: (
									(100 * aiScoreResult.speakerStudentNum) /
									lessonInfo?.teachingClassStudentCount
							  ).toFixed(1)
					}}%</span
				><span v-else class="active">-%</span>，平均每位学生互动<span
					v-if="avgInteractiveTime || avgInteractiveTime === 0"
					class="active"
					>{{ Math.floor(avgInteractiveTime / 60000) }}分{{
						Math.floor(avgInteractiveTime / 1000 - Math.floor(avgInteractiveTime / 60000) * 60)
					}}秒</span
				><span v-else class="active">-分-秒</span>。
			</p>
		</div>
		<div class="chart-wrap">
			<!-- 互动饼图 -->
			<div class="time-chart-wrap">
				<div class="title-wrap">
					<div class="line"></div>
					<p>教室课堂时间分布</p>
				</div>
				<div
					v-if="aiScoreResult?.teachTime || aiScoreResult?.interactiveTime"
					class="interaction-time-chart"
				></div>
				<p v-else class="chart-empty">
					<span class="empty-wrap">本堂课未识别到教师/学生发言</span>
				</p>
			</div>
			<!-- 每位学生互动时长 -->
			<div class="detail-content">
				<div
					class="title-wrap"
					:class="{
						'has-data': interactiveResult && interactiveResult.list && interactiveResult.list.length
					}"
				>
					<div class="line"></div>
					<p>每位学生互动时长</p>
				</div>
				<div
					v-if="interactiveResult && interactiveResult.list && interactiveResult.list.length"
					class="content-wrap"
				>
					<div
						v-for="item in interactiveResult.list"
						:key="item.speakerId"
						class="content-item"
						@click="onClickInteractionTimeHandle(item.earlySpeakTime)"
					>
						<div class="img"></div>
						<p v-if="item.speakTotalTime">
							{{ Math.floor(item.speakTotalTime / 60000) }}分{{
								Math.floor(
									item.speakTotalTime / 1000 - Math.floor(item.speakTotalTime / 60000) * 60
								)
							}}秒
						</p>
						<p v-else>-分-秒</p>
					</div>
				</div>
				<div v-else class="interaction-empty">
					<p class="empty-wrap">本堂课未识别到学生互动</p>
				</div>
			</div>
		</div>
		<!-- 课堂讲授/学生发言时间分布 -->
		<slot></slot>
		<!-- 举手互动 -->
		<div class="hands-wrap">
			<div class="detail interaction-detail">
				<p>
					本堂课学生举手互动<span class="active"
						>{{ handTotalCount || handTotalCount === 0 ? handTotalCount : '-' }}人次</span
					>。
				</p>
			</div>
			<div
				v-if="
					lessonBehaviorDetail && lessonBehaviorDetail.length && lessonBehaviorDetail.length !== 1
				"
				class="hands-up-chart-container"
			>
				<!-- echarts容器 -->
				<div class="hands-up-chart"></div>

				<!-- 休息时间标记线叠加层 -->
				<div
					v-for="(marker, index) in breakTimeMarkers1"
					:key="index"
					class="break-time-marker"
					:style="{
						left: marker.left + 'px',
						top: marker.top + 'px',
						height: marker.height + 'px'
					}"
				>
					<div class="marker-label" :style="{ top: marker.labelTop + 'px' }">
						{{ marker.label }}
					</div>
				</div>
			</div>
			<p v-else class="empty">
				<span class="empty-wrap">本堂课未识别到学生举手互动</span>
			</p>
		</div>
		<!-- 站立互动 -->
		<div class="stand-wrap">
			<div class="detail interaction-detail">
				<p>
					站立互动<span class="active"
						>{{ standTotalCount || standTotalCount === 0 ? standTotalCount : '-' }}人次</span
					>。
				</p>
			</div>
			<div
				v-if="
					lessonBehaviorDetail && lessonBehaviorDetail.length && lessonBehaviorDetail.length !== 1
				"
				class="stand-up-chart-container"
			>
				<!-- echarts容器 -->
				<div class="stand-up-chart"></div>

				<!-- 休息时间标记线叠加层 -->
				<div
					v-for="(marker, index) in breakTimeMarkers2"
					:key="index"
					class="break-time-marker"
					:style="{
						left: marker.left + 'px',
						top: marker.top + 'px',
						height: marker.height + 'px'
					}"
				>
					<div class="marker-label" :style="{ top: marker.labelTop + 'px' }">
						{{ marker.label }}
					</div>
				</div>
			</div>
			<p v-else class="empty">
				<span class="empty-wrap">本堂课未识别到学生站立互动</span>
			</p>
		</div>
	</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { ref, computed, watch, nextTick, onMounted, shallowRef, onUnmounted } from 'vue';
import type {
	CourseListItemType,
	AnalysisResultType,
	InteractiveResultType,
	LessonBehaviorDetailItemType,
	PreviewInfoType,
	BreakTimeMarker
} from './StudentSpeak.type';
import { getErrorMessage, getInteractiveResultAPI } from '@/api/index';

const props = withDefaults(
	defineProps<{
		queryObj: {
			lessonInfo: CourseListItemType | null;
			aiScoreResult: AnalysisResultType | null;
			offsetTime: number;
			videoBeginTime: number;
		} | null;
		lessonBehaviorDetail: LessonBehaviorDetailItemType[];
		stepTime: number;
		realBreakTimeArr: Array<{ startTime: number; endTime: number }> | null;
	}>(),
	{
		queryObj: null,
		lessonBehaviorDetail: () => [],
		stepTime: 5,
		realBreakTimeArr: null
	}
);

const emit = defineEmits<{
	(e: 'changeVideoTime', time: number): void; // 切换视频时间
	(e: 'previewShow', info: PreviewInfoType): void;
}>();

const lessonInfo = computed(() => props.queryObj?.lessonInfo);
const aiScoreResult = computed(() => props.queryObj?.aiScoreResult);
const videoBeginTime = computed(() => props.queryObj?.videoBeginTime);

watch(
	() => props.queryObj,
	(val) => {
		if (val) {
			nextTick(() => {
				getInteractiveResult();
				if (aiScoreResult.value?.teachTime || aiScoreResult.value?.interactiveTime) {
					initInteractionTimeChart();
				}
			});
		}
	},
	{ immediate: true }
);

watch(
	() => props.lessonBehaviorDetail,
	(val) => {
		if (val?.length) {
			nextTick(() => {
				initInteractionBarChart(1);
				initInteractionBarChart(2);
			});
		}
	},
	{ immediate: true }
);

// 窗口大小与1920的比值
const rate = ref(
	(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) / 1920
);

// 休息时间标记点列表（举手图表）
const breakTimeMarkers1 = ref<BreakTimeMarker[]>([]);
// 休息时间标记点列表（站立图表）
const breakTimeMarkers2 = ref<BreakTimeMarker[]>([]);

onMounted(() => {
	window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
	window.removeEventListener('resize', resizeHandler);
	if (interactionTimeChart.value) {
		interactionTimeChart.value.dispose();
	}
	if (interactionChart1.value) {
		interactionChart1.value.dispose();
	}
	if (interactionChart2.value) {
		interactionChart2.value.dispose();
	}
});

const resizeHandler = () => {
	setTimeout(() => {
		rate.value =
			(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) /
			1920;
		initInteractionTimeChart();
		initInteractionBarChart(1);
		initInteractionBarChart(2);
	}, 300);
};

// 课堂互动统计情况
const interactiveResult = ref<InteractiveResultType | null>(null);
// 每名学生平均互动时长
const avgInteractiveTime = ref<number | null>(null);
// 获取课堂互动统计情况
const getInteractiveResult = async () => {
	try {
		const data = await getInteractiveResultAPI(lessonInfo.value?.code as string);

		interactiveResult.value = data || null;
		// 计算每名学生平均互动时长
		let _totalTime = 0;
		if (interactiveResult.value.list && interactiveResult.value.list.length) {
			interactiveResult.value.list.forEach((item) => {
				_totalTime += item.speakTotalTime;
			});
			avgInteractiveTime.value = _totalTime / interactiveResult.value.list.length;
		}
	} catch (err) {
		console.error(getErrorMessage(err));
	}
};

// 计算休息时间标记线的位置 type=1举手 type=2站立
const calculateBreakTimeMarkers = (type: number) => {
	const chartInstance = type === 1 ? interactionChart1.value : interactionChart2.value;
	const markersRef = type === 1 ? breakTimeMarkers1 : breakTimeMarkers2;

	if (!chartInstance || !props.realBreakTimeArr?.length) {
		markersRef.value = [];
		return;
	}

	const markers: BreakTimeMarker[] = [];

	// 获取课程开始时间（使用videoBeginTime作为基准）
	const courseStartTime = videoBeginTime.value || 0;

	// 获取grid配置
	const option = chartInstance.getOption() as Record<string, unknown>;
	const gridOption = (option.grid as Array<Record<string, unknown>>)?.[0];
	if (!gridOption) return;

	const chartDom = document.querySelector(
		type === 1 ? '.hands-up-chart' : '.stand-up-chart'
	) as HTMLElement;
	if (!chartDom) return;

	const chartRect = chartDom.getBoundingClientRect();
	const chartHeight = chartRect.height;

	// 计算grid的实际像素位置
	const gridTop = gridOption.top as number;
	const gridBottom = gridOption.bottom as number;

	const gridHeight = chartHeight - gridTop - gridBottom;

	// 获取x轴的数据列表（举手和站立图表的x轴数据相同，都是去掉第一项的orders*stepTime）
	const xAxisData =
		props.lessonBehaviorDetail
			?.filter((item) => item.orders !== 0)
			.map((item) => item.orders * props.stepTime) || [];
	if (xAxisData.length === 0) return;

	props.realBreakTimeArr.forEach((item) => {
		// 处理开始休息标记
		if (item.startTime) {
			const minutesFromStart = (item.startTime - courseStartTime) / 1000 / 60;
			const pixelX = calculatePixelPosition(minutesFromStart, xAxisData, chartInstance);

			if (pixelX !== null) {
				markers.push({
					left: pixelX,
					top: gridTop,
					height: gridHeight,
					label: '休息',
					labelTop: gridHeight + 20 * rate.value
				});
			}
		}

		// 处理结束休息标记
		if (item.endTime) {
			const minutesFromStart = (item.endTime - courseStartTime) / 1000 / 60;
			const pixelX = calculatePixelPosition(minutesFromStart, xAxisData, chartInstance);

			if (pixelX !== null) {
				markers.push({
					left: pixelX,
					top: gridTop,
					height: gridHeight,
					label: '',
					labelTop: gridHeight + 20 * rate.value
				});
			}
		}
	});

	markersRef.value = markers;
};

// 计算精确的像素位置（支持在两个x轴刻度之间）
const calculatePixelPosition = (
	targetMinutes: number,
	xAxisData: number[],
	chartInstance: echarts.ECharts
): number | null => {
	if (!chartInstance) return null;

	try {
		// 找到目标时间应该在哪两个刻度之间
		let leftIndex = -1;
		let rightIndex = -1;

		for (let i = 0; i < xAxisData.length; i++) {
			if (xAxisData[i] <= targetMinutes) {
				leftIndex = i;
			}
			if (xAxisData[i] >= targetMinutes && rightIndex === -1) {
				rightIndex = i;
				break;
			}
		}

		// 如果目标时间正好在某个刻度上
		if (leftIndex !== -1 && xAxisData[leftIndex] === targetMinutes) {
			const pixelPoint = chartInstance.convertToPixel('grid', [leftIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}

		// 如果目标时间在两个刻度之间
		if (leftIndex !== -1 && rightIndex !== -1 && leftIndex !== rightIndex) {
			const leftPixel = chartInstance.convertToPixel('grid', [leftIndex, 0]);
			const rightPixel = chartInstance.convertToPixel('grid', [rightIndex, 0]);

			if (leftPixel && rightPixel && Array.isArray(leftPixel) && Array.isArray(rightPixel)) {
				// 计算目标时间在两个刻度之间的比例
				const ratio =
					(targetMinutes - xAxisData[leftIndex]) / (xAxisData[rightIndex] - xAxisData[leftIndex]);
				// 根据比例计算精确的像素位置
				const pixelX = leftPixel[0] + (rightPixel[0] - leftPixel[0]) * ratio;
				return pixelX;
			}
		}

		// 如果目标时间在最左边之前
		if (leftIndex === -1 && rightIndex !== -1) {
			const pixelPoint = chartInstance.convertToPixel('grid', [rightIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}

		// 如果目标时间在最右边之后
		if (leftIndex !== -1 && rightIndex === -1) {
			const pixelPoint = chartInstance.convertToPixel('grid', [leftIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}
	} catch (e) {
		console.warn('计算像素位置失败:', e);
	}

	return null;
};

// echarts对象
const interactionTimeChart = shallowRef<echarts.ECharts | null>(null);
// 初始化互动时长饼图
const initInteractionTimeChart = () => {
	const _rate1 =
		(aiScoreResult.value?.calTeachTime || 0) > 0
			? (
					((aiScoreResult.value?.calTeachTime || 0) / (aiScoreResult.value?.calTotalTime || 0)) *
					100
			  ).toFixed(1)
			: 0;
	const _rate2 =
		(aiScoreResult.value?.interactiveTime || 0) > 0
			? (
					((aiScoreResult.value?.interactiveTime || 0) / (aiScoreResult.value?.calTotalTime || 0)) *
					100
			  ).toFixed(1)
			: 0;
	const _rate3 =
		100 - Number(_rate1) - Number(_rate2) > 0
			? (100 - Number(_rate1) - Number(_rate2)).toFixed(1)
			: 0;
	const _teachTime =
		(aiScoreResult.value?.calTeachTime || 0) < 0 ? 0 : aiScoreResult.value?.calTeachTime;
	const _interactiveTime =
		(aiScoreResult.value?.interactiveTime || 0) < 0 ? 0 : aiScoreResult.value?.interactiveTime || 0;
	const _freeTime =
		(aiScoreResult.value?.calTotalTime || 0) - (_teachTime || 0) - (_interactiveTime || 0);
	// 如果没有数据，不渲染图表
	if (!aiScoreResult.value?.totalTime) {
		return;
	}
	const data = [
		{ name: '课堂讲授', value: _rate1, itemStyle: { color: '#00A8FF' } },
		{ name: '学生发言', value: _rate2, itemStyle: { color: '#FFA24F' } },
		{
			name: '空闲时间',
			value: _rate3,
			itemStyle: { color: '#FFFFFF', borderWidth: 1, borderColor: '#E5F6FF' },
			labelLine: { lineStyle: { color: '#E5F6FF' } }
		}
	];

	if (interactionTimeChart.value) {
		interactionTimeChart.value.dispose();
	}
	interactionTimeChart.value = echarts.init(
		document.querySelector('.interaction-time-chart') as HTMLElement
	);
	const option = {
		tooltip: {
			formatter(params: { name: string }) {
				if (params.name === '课堂讲授') {
					if ((aiScoreResult.value?.calTeachTime || 0) < 0) {
						return '课堂讲授：0分0秒';
					}
					return `课堂讲授：${Math.floor(
						(aiScoreResult.value?.calTeachTime || 0) / 60000
					)}分${Math.floor(
						(aiScoreResult.value?.calTeachTime || 0) / 1000 -
							Math.floor((aiScoreResult.value?.calTeachTime || 0) / 60000) * 60
					)}秒`;
				}
				if (params.name === '学生发言') {
					if ((aiScoreResult.value?.interactiveTime || 0) < 0) {
						return '学生发言：0分0秒';
					}
					return `学生发言：${Math.floor(
						(aiScoreResult.value?.interactiveTime || 0) / 60000
					)}分${Math.floor(
						(aiScoreResult.value?.interactiveTime || 0) / 1000 -
							Math.floor((aiScoreResult.value?.interactiveTime || 0) / 60000) * 60
					)}秒`;
				}
				if (_freeTime < 0) {
					return '空闲时间：0分0秒';
				}
				return `空闲时间：${Math.floor(_freeTime / 60000)}分${Math.floor(
					_freeTime / 1000 - Math.floor(_freeTime / 60000) * 60
				)}秒`;
			},
			textStyle: {
				fontSize: 14 * rate.value,
				fontFamily: 'Alibaba PuHuiTi'
			}
		},
		graphic: {
			type: 'text',
			left: 'center',
			top: 'center',
			style: {
				text: '时间占比\n分布图',
				textAlign: 'center',
				font: `400 ${14 * rate.value}px "Alibaba PuHuiTi"`,
				lineHeight: 16,
				fill: '#666666'
			}
		},
		series: [
			{
				name: '',
				type: 'pie',
				radius: ['40%', '70%'],
				center: ['50%', '50%'], // 修改为居中
				label: {
					fontSize: 12 * rate.value,
					fontFamily: 'Alibaba PuHuiTi',
					fontWeight: 400,
					color: '#222222',
					formatter: (params: { name: string; value: number }) => {
						let _value;
						switch (params.name) {
							case '课堂讲授':
								_value = 'b';
								break;
							case '学生发言':
								_value = 'c';
								break;
							default:
								_value = 'd';
						}
						return `{a|${params.name}} {${_value}|${params.value}%}`;
					},
					rich: {
						b: {
							fontSize: 14 * rate.value,
							fontFamily: 'Pangmen Title',
							color: '#00A8FF'
						},
						c: {
							fontSize: 14 * rate.value,
							fontFamily: 'Pangmen Title',
							color: '#FFA24F'
						},
						d: {
							fontSize: 14 * rate.value,
							fontFamily: 'Pangmen Title',
							color: '#222222'
						}
					}
				},
				emphasis: {
					itemStyle: {
						color: 'inherit'
					}
				},
				data
			}
		]
	};
	interactionTimeChart.value.setOption(option);
};

// 点击学生互动时长
const onClickInteractionTimeHandle = (time: number) => {
	const _currentTime = time / 1000;
	// 通知视频组件弹框
	if (_currentTime) {
		emit('changeVideoTime', _currentTime);
	} else {
		emit('changeVideoTime', 0);
	}
};

// 举手总人次
const handTotalCount = ref<number>(0);
// 站立总人次
const standTotalCount = ref<number>(0);
// 预览信息
const previewInfo = ref<PreviewInfoType | null>(null);
// echarts对象
const interactionChart1 = shallowRef<echarts.ECharts | null>(null);
const interactionChart2 = shallowRef<echarts.ECharts | null>(null);
// 初始化互动柱状图 type=1举手 type=2站立
const initInteractionBarChart = (type: number) => {
	// 如果没有数据，就不渲染图形
	if (
		!props.lessonBehaviorDetail ||
		!props.lessonBehaviorDetail.length ||
		props.lessonBehaviorDetail.length === 1
	) {
		return;
	}

	const _xAxisList = props.lessonBehaviorDetail.map((item) => item.orders * props.stepTime);
	// 不展示orders为0的项，即第一项
	_xAxisList.shift();
	const _yAxisList1: number[] = [];
	const _yAxisList2: number[] = [];
	props.lessonBehaviorDetail.forEach((item) => {
		// 不展示orders为0的项
		if (item.orders !== 0) {
			let count1 = 0;
			let count2 = 0;
			item.behaviorData.forEach((behavior) => {
				if (behavior.behaviorType === 'hand') {
					count1 += behavior.num;
				} else if (behavior.behaviorType === 'stand') {
					count2 += behavior.num;
				}
			});
			_yAxisList1.push(count1);
			_yAxisList2.push(count2);
		}
	});
	if (type === 1) {
		if (interactionChart1.value) {
			interactionChart1.value.dispose();
		}
		interactionChart1.value = echarts.init(
			document.querySelector('.hands-up-chart') as HTMLElement
		);
		// 计算总人次
		let _count = 0;
		_yAxisList1.forEach((item) => {
			_count += item;
		});
		handTotalCount.value = _count;
	} else {
		if (interactionChart2.value) {
			interactionChart2.value.dispose();
		}
		interactionChart2.value = echarts.init(
			document.querySelector('.stand-up-chart') as HTMLElement
		);
		// 计算总人次
		let _count = 0;
		_yAxisList2.forEach((item) => {
			_count += item;
		});
		standTotalCount.value = _count;
	}
	const option = {
		grid: {
			left: 50 * rate.value,
			right: 30 * rate.value,
			top: 40 * rate.value,
			bottom: props.realBreakTimeArr?.length ? 45 * rate.value : 40 * rate.value
		},
		tooltip: {
			formatter: '{b}分：{c}人',
			textStyle: {
				fontSize: 14 * rate.value,
				fontFamily: 'Alibaba PuHuiTi'
			}
		},
		xAxis: {
			data: _xAxisList,
			nameTextStyle: {
				color: 'transparent'
			},
			axisLabel: {
				margin: 8 * rate.value,
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666',
				formatter: (value: number) => {
					return `${value}分`;
				}
			},
			axisTick: {
				length: 3 * rate.value,
				alignWithLabel: true,
				lineStyle: {
					color: '#E3E3E3'
				}
			},
			axisLine: {
				lineStyle: {
					color: '#E3E3E3'
				}
			}
		},
		yAxis: {
			name: '人数',
			minInterval: 1,
			nameTextStyle: {
				padding: [0, 30 * rate.value, 0, 0],
				fontSize: 12 * rate.value,
				fontFamily: 'Alibaba PuHuiTi',
				fontWeight: 400,
				color: '#666666'
			},
			axisLabel: {
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666'
			},
			splitLine: {
				lineStyle: {
					color: ['#EFEFEF']
				}
			}
		},
		series: [
			{
				name: type === 1 ? '举手' : '站立',
				type: 'bar',
				barWidth: 20 * rate.value,
				label: {
					show: true,
					position: 'top',
					fontSize: 12 * rate.value,
					fontWeight: 400,
					fontFamily: 'Alibaba PuHuiTi',
					color: '#666666'
				},
				itemStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: '#A8E1FF' // 0% 处的颜色
							},
							{
								offset: 1,
								color: '#00A8FF' // 100% 处的颜色
							}
						],
						global: false // 缺省为 false
					}
				},
				data: type === 1 ? _yAxisList1 : _yAxisList2
			}
		]
	};
	// 如果最大值小于5，设置y轴最大值为5
	let max = 0;
	if (type === 1) {
		max = Math.max(..._yAxisList1);
	} else {
		max = Math.max(..._yAxisList2);
	}
	if (max <= 5) {
		(option.yAxis as Record<string, unknown>).max = 5;
	}

	if (type === 1) {
		interactionChart1.value?.setOption(option);
	} else {
		interactionChart2.value?.setOption(option);
	}

	// 图表渲染完成后计算标记线位置
	nextTick(() => {
		setTimeout(() => {
			calculateBreakTimeMarkers(type);
		}, 100);
	});

	const clickEvent = (params: echarts.ECElementEvent) => {
		// 柱状图才触发事件
		if (params.componentSubType === 'bar' && params.data) {
			// 由于第一项orders为0时未展示，所以index需要+1错开一位
			const _behaviorDetail = props.lessonBehaviorDetail[params.dataIndex + 1];
			if (_behaviorDetail && _behaviorDetail.behaviorData && _behaviorDetail.behaviorData.length) {
				if (params.seriesName === '举手') {
					const _data = _behaviorDetail.behaviorData.filter((item) => {
						// 计算每张图片对应的视频时间
						if (item.occurTime) {
							const _occurTime = new Date(item.occurTime).getTime();
							item.videoTime =
								_occurTime - (videoBeginTime.value || 0) > 0
									? (_occurTime - (videoBeginTime.value || 0)) / 1000 - 1
									: 0;
						}
						return item.behaviorType === 'hand';
					});
					if (_data) {
						previewInfo.value = {
							transFileUrl: _data,
							name: '举手互动',
							type: 2,
							analysisType: 2 // 1:老师 2:学生
						};
						emit('previewShow', previewInfo.value);
					}
				} else {
					const _data = _behaviorDetail.behaviorData.filter((item) => {
						// 计算每张图片对应的视频时间
						if (item.occurTime) {
							const _occurTime = new Date(item.occurTime).getTime();
							item.videoTime =
								_occurTime - (videoBeginTime.value || 0) > 0
									? (_occurTime - (videoBeginTime.value || 0)) / 1000 - 1
									: 0;
						}
						return item.behaviorType === 'stand';
					});
					if (_data) {
						previewInfo.value = {
							transFileUrl: _data,
							name: '站立互动',
							type: 2,
							analysisType: 2 // 1:老师 2:学生
						};
						emit('previewShow', previewInfo.value);
					}
				}
			}
		}
	};
	// 给柱状图绑定点击事件
	if (type === 1) {
		interactionChart1.value?.on('click', clickEvent);
	} else {
		interactionChart2.value?.on('click', clickEvent);
	}
};
</script>

<style lang="scss" scoped>
.student-speak-wrapper {
	margin-top: 1.6rem;

	.chart-wrap {
		display: flex;
		gap: 2rem;

		.time-chart-wrap,
		.detail-content {
			flex: 1;
			min-width: 0;
			background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);

			.title-wrap {
				padding: 1.8rem 0 1rem 2.6rem;
				display: flex;
				align-items: center;

				.line {
					margin-right: 0.8rem;
					width: 0.4rem;
					height: $font-size-small-1;
					background: $color-brand;
					border-radius: 0.2rem;
				}

				p {
					font-size: $font-size-base;
					color: $color-brand;
				}
			}

			.interaction-time-chart,
			.chart-empty {
				position: relative;
				width: 100%;
				height: 18rem;
			}
		}

		.detail-content {
			display: flex;
			flex-direction: column;

			.title-wrap {
				padding-bottom: 1rem;

				&.has-data {
					padding-bottom: 1.8rem;
				}
			}

			.content-wrap {
				padding: 0 2.6rem 1.8rem;
				display: flex;
				flex-wrap: wrap;
				gap: 1.8rem calc((100% - 6rem * 5) / 4);

				.content-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					cursor: pointer;

					.img {
						margin-bottom: 0.9rem;
						width: 3rem;
						height: 3.1rem;
						background: url('@/assets/images/lessonAnalysisDetails/student-header.png') no-repeat
							center;
						background-size: 100% 100%;
					}

					p {
						width: 6rem;
						height: 2rem;
						background: rgba(209, 231, 253, 0.5);
						border-radius: 0.4rem;
						font-size: $font-size-small-2;
						color: $text-color-regular;
						text-align: center;
						line-height: 2rem;
					}
				}

				.content-item:hover {
					.img {
						background-image: url('@/assets/images/lessonAnalysisDetails/student-header-active.png');
					}
					p {
						background-color: #d1e7fd;
					}
				}
			}

			.interaction-empty {
				position: relative;
				flex: 1;
				width: 100%;
			}
		}
	}

	.hands-wrap,
	.stand-wrap {
		.hands-up-chart-container,
		.stand-up-chart-container {
			position: relative;
			height: 20rem;
			background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);

			.hands-up-chart,
			.stand-up-chart {
				position: relative;
				width: 100%;
				height: 100%;
			}

			// 休息时间标记线
			.break-time-marker {
				position: absolute;
				width: 0.2rem;
				background-color: rgba($color: $color-success, $alpha: 0.3);
				pointer-events: none;
				z-index: 10;

				.marker-label {
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					font-size: $font-size-small-2;
					color: $text-color-success;
					font-weight: bold;
					white-space: nowrap;
					padding: 0.2rem 0.4rem;
				}
			}
		}

		.empty {
			position: relative;
			height: 20rem;
			background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);
			text-align: center;
		}
	}
}
</style>
